home *** CD-ROM | disk | FTP | other *** search
/ NeXT Education Software Sampler 1992 Fall / NeXT Education Software Sampler 1992 Fall.iso / Programming / Classes / CryptSums / cryptsum.c next >
Encoding:
C/C++ Source or Header  |  1992-05-21  |  2.0 KB  |  68 lines

  1. /* cryptsum.c -- copyright 1992 by C.D.Lane */
  2.  
  3. #include <c.h>
  4. #include <libc.h>
  5. #include <ctype.h>
  6. #include <stdio.h>
  7.  
  8. #include "cryptsum.h"
  9.  
  10. #define RANGE (127)
  11. #define MAXUSHORT ((unsigned short) 0x8000)
  12.  
  13. union overlay { unsigned short halfword; char salt[2]; };
  14.  
  15. char *cs_cryptkey(const char *key, unsigned short checksum)
  16. {
  17.     union overlay u_sum;
  18.     
  19.     u_sum.halfword = checksum;
  20.     
  21.     if(!isalpha(u_sum.salt[0] &= RANGE)) u_sum.salt[0] = ((u_sum.salt[0] * ('z' - 'a')) / RANGE) + 'a';
  22.     if(!isalpha(u_sum.salt[1] &= RANGE)) u_sum.salt[1] = ((u_sum.salt[1] * ('Z' - 'A')) / RANGE) + 'A';
  23.             
  24.     return(crypt((char *) key, u_sum.salt) + sizeof(u_sum));
  25. }
  26.  
  27. char *cs_tablelookup(const char *segment, const char *section, const char *table)
  28. {
  29.     static char key[BUFSIZ];
  30.     
  31.     (void) sprintf(key, "%s %s", segment, section);
  32.     
  33.     while(table != NULL && *table != '\0' && strncmp(key, table, strlen(key)) != 0)
  34.         if((table = index(table, '\n')) != NULL) table++;
  35.     
  36.     if(table == NULL || *table == '\0' || (table = index(table + strlen(key), ' ')) == NULL) return(NULL);
  37.     
  38.     return((char *) ++table);
  39. }
  40.  
  41. unsigned short cs_checksum(unsigned short checksum, unsigned char byte)
  42. {
  43.     return(byte ^ ((checksum << 1) | ((checksum & MAXUSHORT) != 0)));
  44. }
  45.  
  46. int cs_checkkey(const char *segment, const char *section, const char *key)
  47. {
  48.     int i, size;
  49.     void *pointer;
  50.     unsigned short halfword = 0;
  51.     char *password, *encrypted, table[MAXBSIZE];
  52.  
  53.     if((pointer = getsectdata(segment, section, &size)) == NULL) return(CS_NOSECTION);
  54.         
  55.     for(i = 0; i < size; i++) halfword = cs_checksum(halfword, *((unsigned char *) pointer++));
  56.             
  57.     if((pointer = getsectdata(CS_SEGMENT, CS_SECTION, &size)) == NULL) return(CS_NOCHECKSUM);
  58.         
  59.     (void) strcat(strncpy(table, (char *) pointer, MIN(size, MAXBSIZE - 1)), "");
  60.     
  61.     if((encrypted = cs_tablelookup(segment, section, table)) == NULL) return(CS_NOENTRY);
  62.     
  63.     password = cs_cryptkey(key, halfword);
  64.     
  65.     if(strncmp(password, encrypted, strlen(password)) != 0) return(CS_NOMATCH);
  66.  
  67.     return(CS_SUCCESS);
  68. }